/**
 * 
 */
package info.niwota.home;

import instant.openvfs.home.Debug;
import instant.openvfs.home.web.BaseFileContentProvider;
import instant.openvfs.home.web.FileHandler;
import instant.openvfs.home.web.FileMatrixCursor;

import java.util.Arrays;

import x.java.io.File;
import android.net.Uri;
import android.util.Log;

/**
 * @author qiangli
 * 
 */
public class FileContentProvider extends BaseFileContentProvider {
	private static final String TAG = "FileContentProvider";

	private FileHandler handler = new FileHandler();
	
	private class MyMatrixCursor extends FileMatrixCursor {

		private File[] files;
		private int count = -1;

		public MyMatrixCursor(Uri uri, String[] projection, String selection,
				String[] selectionArgs, String sortOrder) {
			super(uri, projection, selection, selectionArgs, sortOrder);
			init();
		}

		private void init() {
			File file = new File(uri.getPath());
			files = file.listFiles();
			if (files == null) {
				return;
			}
			count = files.length;
			Arrays.sort(files);
		}

		@Override
		protected int getRowCount() {
			return count;
		}

		@Override
		protected Object[] mapRow(int row) {
			final File fi = files[row];
			final String id = row + "";
			final boolean encrypted = false;
			final String p = fi.getPath().substring(1);
			Uri uri = Uri.withAppendedPath(CONTENT_URI, p);
			if (Debug.DEBUG) {
				Log.d(TAG, "mapRow  [" + row + "]" + uri);
			}
			final String content = null; //fi.getContent() too expensive
			Object[] obj = new Object[] { id, fi.getName(), fi.length(),
					fi.lastModified(), fi.canRead(), fi.canWrite(),
					fi.canExecute(), fi.isDirectory(), fi.isFile(),
					fi.isLink(), fi.isHidden(), fi.isEmpty(), fi.isLocal(),
					fi.isNative(), encrypted, fi.getSortKey(),
					fi.getPhoneticName(), fi.getDisplayName(), fi.getIcon(),
					fi.getAttributes(), content,
					fi.getContentEncoding(), fi.getContentType(), uri };
			return obj;
		}
	}

	public FileContentProvider() {
	}

	@Override
	protected FileMatrixCursor getMatrixCursor(Uri uri, String[] projection,
			String selection, String[] selectionArgs, String sortOrder) {
		return new MyMatrixCursor(uri, projection, selection, selectionArgs,
				sortOrder);
	}

	@Override
	protected Object getData(Uri uri, String mode) throws Exception {
		Object obj = handler.handle(uri, mode);
		return obj;
	}

}
